package com.example.contacts.DB;

import java.io.Serializable;

import android.R.integer;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.contacts.sql_bean.People;


public class DBTool {

	private String databasePath;
	private SQLiteDatabase database;

	public DBTool(String databasePath){
		this.databasePath=databasePath;
	}

	public void openDatabase(){
		//获取SQliteDatabase对象

		if(database==null||!database.isOpen()){
			database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
		}

	}

	public void closeDatabase(){
		if(database!=null||database.isOpen()){
			database.close();
		}
	}
	
	//1查询所有人信息   返回游标 ->Cursor
	public  Cursor getPeople(){
		Cursor cursor=null;
		//查询。。
		//SQL:select * from People where name='中国移动' 条件   第二个参数new String[]{"id","name"}
		cursor=database.query("people",null , null, null, null, null, null);//查询所有
		return cursor;
	}
	
	//2查询符合条件的人
	public Cursor getPeople(int id){
		Cursor cursor=null;
		cursor=database.query("people",null , "id=?", new String[]{String.valueOf(id)}, null, null, null);//查询所有
		return cursor;
	}
	
	public Cursor getPeople(String str){
		Cursor cursor=null;
		//cursor=database.query("people",null , "name like '%?%'", new String[]{name}, null, null, null);
		String sql  = "select * from people where name like ? or number like ?"; 
        String [] selectionArgs  = new String[]{"%" + str + "%", "%" + str + "%"};
        cursor = database.rawQuery(sql, selectionArgs); 
		return cursor;
	}
	
	public Cursor getPeople(String name,String number){
		Cursor cursor=null;
		cursor=database.query("people",null , "name=? and number=?", new String[]{name,number}, null, null, null);
		return cursor;
	}
	
	//3修改
	public long updatePeople(People people){
		//updata people set name='灰太狼' number=1340000000 where id =1
		ContentValues values=new ContentValues();
		values.put("name", people.getName());
		values.put("number", people.getNumber());
		values.put("note", people.getNote());
		return database.update("people",values , "id=?", new String[]{String.valueOf(people.getId())});
	}
	
	//4新增联系人  //返回》0 成果  返会0 失败
	public long addPeople(People people){
		//insert into people values(null,'红太狼','100000000','老婆');
		ContentValues values=new ContentValues();
		values.put("name", people.getName());
		values.put("number",people.getNumber());
		values.put("note", people.getNote());
		return database.insert("people", null, values);
		
	}
	
	//5删除联系人
	public long removePeople(int id){
		//delet from people where id=1 
		return database.delete("people", "id=?", new String[]{String.valueOf(String.valueOf(id))});
	}
	
	public long removePeople(String name,String number){
		//delet from people where id=1 
		return database.delete("people", "name=? and number=?", new String[]{name,number});
	}
	
}
